<?php
declare (strict_types=1);
namespace app\admin\logic\system\notify;

use app\admin\logic\system\Config as SystemConfig;
use app\admin\logic\system\Log;
use app\admin\model\system\notify\NotifyNode as NotifyNodeModel;
use app\admin\model\system\notify\NotifyNodeData;
use app\common\exception\LogicException;
use think\db\exception\DbException;
use think\Model;
use think\Paginator;

/**
 * 消息节点
 */
class NotifyNode extends NotifyNodeModel
{
    /**
     * 获取节点列表
     *
     * @param array $map [description]
     * @return Paginator [type]                              [description]
     * @throws DbException
     */
    public function getList(array $map)
    {
        return $this
            ->with(['notifyNodeData'])
            ->where($map)
            ->field(['id', 'title', 'key', 'has_sms', 'content', 'help', 'status'])
            // ->order('update_time', 'DESC')
            ->paginate($this->getListRows());
    }

    /**
     * 保存配置的节点
     *
     * @param int   $id [description]
     * @param array $data
     * @return NotifyNode|array|Model [type]                               [description]
     */
    public function saveNode(int $id, array $data)
    {
        $node = $this->where('id', $id)->findOrFail();

        $check       = $data;
        $check['id'] = $id;
        // 验证数据
        $this->getValidate()->failException()->check($check);

        $notifyNodeData = [
            'content'           => $data['content'],
            'sms_template_code' => $data['sms_template_code'] ?? '',
            'open_info'         => $data['open_info']
        ];

        $has = $node->notifyNodeData;
        if ($has) {
            $notifyNodeData['id'] = $has->id;
        }

        if (!$node->notifyNodeData()->save($notifyNodeData)) {
            throw new LogicException('修改失败');
        }
        Log::write(sprintf('更新通知配置【%s】', $node->title), 'notify', 'update', true);

        return $node;
    }

    /**
     * getInfoByIdOrFail
     *
     * @param int $id
     * @return NotifyNode|array|Model
     */
    public function getInfoByIdOrFail(int $id)
    {
        $info = $this->with(['notifyNodeData'])->where('id', $id)->findOrFail();

        return $this->handlerInfo($info);
    }

    /**
     * getInfoByKey
     *
     * @param string $key
     * @return NotifyNodeModel
     */
    public function getInfoByKey(string $key)
    {
        $info = $this->with(['notifyNodeData'])->where('key', $key)->findOrEmpty();

        return $this->handlerInfo($info);
    }

    /**
     * getNotifyNodeDataByKey
     *
     * @param string $key
     * @return NotifyNodeModel
     */
    public function getNotifyNodeDataByKey(string $key)
    {
        $info = $this->getInfoByKey($key);
        if (!$info->notifyNodeData) {
            // $data = app(NotifyNodeData::class)->where('config_id', $info->id)->findOrEmpty();
            // 如果没有获取到机构配置,就取平台的
            $data                    = NotifyNodeData::withoutGlobalScope(['mhm'])->where('config_id', $info->id)->where('mhm_id', 1)->findOrEmpty();
            $info->sms_template_code = $data->sms_template_code;
            $info->open_info         = $data->open_info;
            $info->mhm_id            = $data->mhm_id;
            $info->config_id         = $data->config_id;
            $info->content           = $data->content ?: $info->content;
            $info->update_time       = $data->update_time;
        } else if (!request()->is_platform) {
            // 是否开启了启用平台短信
            $config      = SystemConfig::get('system.package.sms.sync', ['use_platform' => 0], request()->mhm_id, true);
            $usePlatform = isset($config['use_platform']) ? (bool)$config['use_platform'] : false;
            if ($usePlatform) {
                // 短信配置使用了平台，则获取平台通知配置
                $mhmData = NotifyNodeData::withoutGlobalScope(['mhm'])->where('config_id', $info->id)->where('mhm_id', 1)->findOrEmpty();
                // $info->open_info         = $mhmData->open_info ?: $info->open_info;
                $info->sms_template_code = $mhmData->sms_template_code ?: $info->sms_template_code;
                // $info->content           = $mhmData->content ?: $info->content;
            }
        }

        return $info;
    }

    protected function handlerInfo(NotifyNodeModel $info)
    {
        if ($info->data_content) {
            $info->content     = $info->data_content;
            $info->update_time = $info->data_update_time;
        }

        return $info;
    }
}
